﻿using System;
using System.Data;

namespace msBsc.WebUi
{
    public partial class wfShpPageMall : msBsc.Cls.BPageHt
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                SetContrlValue("txtType", this.GetFormParam("T"));
                BindControls();
                //System.Random rd = new Random();
                //sRadom.Value = this.GetRadomString();
            }
        }

        private void BindControls()
        {
            if (!IsPostBack)
            {
                //DataSet ds;
                //using (Epm.AppLogic.Framework.CDbAccess oCDbAccess = new Epm.AppLogic.Framework.CDbAccess())
                //{
                //    ds = oCDbAccess.QueryBySQL("SELECT LEVEL_ONE_ID,LEVEL_ONE_NME FROM SHP_GOODS_TYPE_LEVEL_ONE");
                //}

                //BoundComboBox("LEVEL_ONE_ID", ds, "LEVEL_ONE_NME", "LEVEL_ONE_ID", "", "", false);
            }
        }
        //重构基类的回调处理函数，以strAction属性来判断是什么类型的回调，该变量的值对应前台的ACTION参数，如：按钮的名称等
        public override void InitialByParam()
        {
            if (this.gtGridRet != null)
            {
                if (this.gtGridRet.action == "load" || this.gtGridRet.action == "export")//处理GRID的数据原获取和数据导出
                {
                    DataSet ds = GetDisplayData(this.GetParamHtValue("gtGridID"), this.strAction, this.sCurrPageRadom);
                    if (ds != null && ds.Tables.Count > 0)
                        SetReturnDatatable(ds.Tables[0], "PAGE_NO");//CONSTANT_CATEGORY_ID为表的KEY字段，可填可不填
                }
                //处理数据保存
                if (this.gtGridRet.action == "save" && (gtGridRet.insertedRecords.Length > 0 || gtGridRet.updatedRecords.Length > 0 || gtGridRet.deletedRecords.Length > 0))
                {
                    DataSet ds = GetDisplayData(this.GetParamHtValue("gtGridID"), this.strAction, this.sCurrPageRadom);
                    try
                    {
                        if (ds != null && ds.Tables.Count > 0)
                        {
                            //处理记录新增，前台已传入新增的ROW
                            for (int i = 0; i < gtGridRet.insertedRecords.Length; i++)
                            {
                                DataRow drNew = ds.Tables[0].NewRow();
                                msBsc.AppLogic.Cfg.HttpTools.CopyHashToDataRow(gtGridRet.insertedRecords[i], drNew);
                                //drNew["PAGE_NO"] = (new Epm.AppLogic.Framework.CDbAccess()).NewID();
                                drNew["MALL_TYPE"] = GetParamHtValue("T");
                                if (drNew["MALL_TYPE"].ToString() == string.Empty)
                                {
                                    drNew["MALL_TYPE"] = "0";
                                }
                                ds.Tables[0].Rows.Add(drNew);
                            }

                            //处理记录更新，前台已传入更新的ROW
                            for (int i = 0; i < gtGridRet.updatedRecords.Length; i++)
                            {
                                string stridtm = gtGridRet.updatedRecords[i]["PAGE_NO"].ToString();
                                if (stridtm != string.Empty)
                                {
                                    DataRow[] arrtemr = ds.Tables[0].Select("PAGE_NO='" + stridtm + "'");
                                    if (arrtemr.Length > 0)
                                    {
                                        msBsc.AppLogic.Cfg.HttpTools.CopyHashToDataRow(gtGridRet.updatedRecords[i], arrtemr[0]);
                                    }
                                }
                            }

                            //处理记录删除，前台已传入删除的ROW
                            for (int i = 0; i < gtGridRet.deletedRecords.Length; i++)
                            {
                                string stridtm = gtGridRet.deletedRecords[i]["PAGE_NO"].ToString();
                                if (stridtm != string.Empty)
                                {
                                    DataRow[] arrtemr = ds.Tables[0].Select("PAGE_NO='" + stridtm + "'");
                                    if (arrtemr.Length > 0)
                                    {
                                        arrtemr[0].Delete();
                                    }
                                }
                            }
                            if (ds.HasChanges())
                            {
                                //System.Transactions.TransactionOptions transactionOption = new System.Transactions.TransactionOptions();
                                //transactionOption.IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted;
                                //transactionOption.Timeout = new TimeSpan(0, 10, 0);
                                //using (System.Transactions.TransactionScope ts = new System.Transactions.TransactionScope(System.Transactions.TransactionScopeOption.Required, transactionOption))
                                //{ 
                                    using (msBsc.AppLogic.DataAlc.CBizShpPageMall objtem1 = new msBsc.AppLogic.DataAlc.CBizShpPageMall())
                                    {
                                        objtem1.Update(ds);
                                    } 
                                    ds.AcceptChanges();

                                //    ts.Complete();
                                //    ts.Dispose();
                                     
                                //}
                            }
                        }
                    }
                    catch (Exception err)
                    {
                        ds.RejectChanges();
                        gtGridRetSaveException = err.Message;
                    }
                }
                if (gtGridRetSaveSuccess && (this.gtGridRet.action == "save" || strAction == "btnSave"))//根据传入的回调类型进行处理，这里响应编辑按钮
                {
                    //保存后将页面置为查看状态
                    SetMode("VIEW");
                }
            }
            else if (strAction == "btnEdit")//根据传入的回调类型进行处理，这里响应编辑按钮
            {
                SetMode("EDIT");
            }
            else if (strAction == "btnNotSave")//根据传入的回调类型进行处理，这里响应编辑按钮
            {
                SetMode("VIEW");
            }
            //else if (strAction == "savePageHtm")//根据传入的回调类型进行处理，这里响应编辑按钮
            //{
            //    SetMode("VIEW");
            //}
            else if (strAction == "btnCreatePageHtml")//根据传入的回调类型进行处理，这里响应编辑按钮
            {
                dobtnCreatePageHtml(this.GetParamHtValue("CHECK_ID"));
            } 

            base.InitialByParam();
        }
        private void dobtnCreatePageHtml(string smallids)
        {
            using (msBsc.AppLogic.DataAlc.CBizShpPageMall objmall = new AppLogic.DataAlc.CBizShpPageMall())
            {
                msBsc.SvRef.SRWebClient oSRWebClient = new SvRef.SRWebClient();
                DataSet ds = objmall.SelectByIds(smallids);
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    if (ds.Tables[0].Rows[i]["ASPX_PAGE_URL"].ToString() != string.Empty)
                    {
                        string strToPath = Server.MapPath("/HtmPages/") + "page_" + ds.Tables[0].Rows[i]["PAGE_NO"].ToString()+".html";
                        oSRWebClient.DownloadFile(msBsc.AppLogic.Cfg.SystemFileDir.FileDir.httpUrlBase+ ds.Tables[0].Rows[i]["ASPX_PAGE_URL"].ToString().TrimStart('/'), strToPath, false);
                    }
                } 
            }

        }

        //private void savePageHtm()
        //{
        //    string strHeadHtml = this.GetPostHtValue("TEMPLATE_HTML");
        //    string strVpath = "/HtmPages/page_" + this.GetPostHtValue("PAGE_NO")+".htm";//只是文件名，目录固定
        //    if (strHeadHtml != string.Empty && strVpath != string.Empty)
        //    {
        //        string strFFullPath = System.Web.HttpContext.Current.Server.MapPath(strVpath);
        //        System.IO.File.WriteAllText(strFFullPath, strHeadHtml, System.Text.Encoding.UTF8);
        //    }

        //    this.ExecJScript("layer.msg('成功保存模版！',1,{type:1,shade:false});");
        //}

        //修改页面状态
        private void SetMode(string strMode)
        {
            EditMode = strMode; switch (strMode)
            {
                case "EDIT":
                    EnabledLinkBtn("btnEdit", false);
                    EnabledLinkBtn("btnSave", true);
                    EnabledLinkBtn("btnNotSave", true);
                    EnabledLinkBtn("btnConfirm", false);
                    EnabledLinkBtn("btnCancel", false);
                    this.ExecJScript("doEditGt('myGrid1');");
                    break;
                case "ADD":
                    EnabledLinkBtn("btnEdit", false);
                    EnabledLinkBtn("btnSave", true);
                    EnabledLinkBtn("btnNotSave", false);
                    EnabledLinkBtn("btnConfirm", false);
                    EnabledLinkBtn("btnCancel", false);
                    this.ExecJScript("doEditGt('myGrid1');");
                    break;
                case "VIEW":
                    EnabledLinkBtn("btnEdit", true);
                    EnabledLinkBtn("btnSave", false);
                    EnabledLinkBtn("btnNotSave", false);
                    EnabledLinkBtn("btnConfirm", true);
                    EnabledLinkBtn("btnCancel", true);
                    this.ExecJScript("doCancelGt('myGrid1');");
                    break;
            }
        }
        //获取数据原,"DP_DATA"字符一定不要改变，否则系统不能自动清除缓存
        public DataSet GetDisplayData(string strgtGridID, string strSrcF, string strsRadom)
        {
            if (strgtGridID == "myGrid1")
            {
                DataSet ds;
                if (strSrcF == "mFinder" || !this.SessionIsExists(strsRadom + "DP_DATA", "1"))//点击查询按钮时，或需要数据而没有缓存时，根据条件取出数据记录
                {  
                    using (Epm.AppLogic.Framework.CDbAccess oCDbAccess = new Epm.AppLogic.Framework.CDbAccess())
                    {
                        string strPageNme = GetParamHtValue("PAGE_NME");
                        ds = oCDbAccess.QueryBySQL("SELECT * FROM SHP_PAGE_MALL WHERE (MALL_TYPE='"+GetParamHtValue("T")+"') AND ('" + strPageNme + "'='' OR PAGE_NME='" + strPageNme + "' OR PAGE_NO='" + strPageNme + "') ORDER BY SEQ_NUM ASC");
                        ds.Tables[0].TableName = "SHP_PAGE_MALL";
                    }
                    ds.AcceptChanges();
                    SetSession(strsRadom + "DP_DATA", ds, "1");
                    //查询时，将页面置为查看状态
                    if (strSrcF == "mFinder")
                        SetMode("VIEW");
                }
                else
                {
                    ds = (DataSet)this.GetSession(strsRadom + "DP_DATA", "1");
                }
                return ds;
            }
            else
            {
                return null;
            }
        }

    }
}